package com.lhsy.djcloud.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.crypto.SecureUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lhsy.djcloud.common.ReturnT;
import com.lhsy.djcloud.common.SecurityConstant;
import com.lhsy.djcloud.common.UUIDTools;
import com.lhsy.djcloud.controller.vo.DepartmentVo;
import com.lhsy.djcloud.entity.Department;
import com.lhsy.djcloud.entity.Employee;
import com.lhsy.djcloud.entity.User;
import com.lhsy.djcloud.entity.dto.DepartmentDto;
import com.lhsy.djcloud.entity.dto.UserDto;
import com.lhsy.djcloud.service.DepartmentService;
import com.lhsy.djcloud.service.EmployeeService;
import com.lhsy.djcloud.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wangzw
 * @since 2020-09-14
 */
@RestController
@RequestMapping("/party")
@Api(value = "Server-API",tags = "党组织管理")
public class DepartmentController extends BaseController{
    @Autowired private DepartmentService departmentService;
    @Autowired private EmployeeService employeeService;
    @Autowired private UserService userService;

    @ApiOperation(value = "党组织列表加载/根据用户角色加载自己所属的部门列表")
    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public ReturnT<List<DepartmentDto>> list(HttpServletRequest request,
                                             String params,
                                             @RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,@RequestParam(value = "pageSize",defaultValue = "10")Integer pageSize){
        //校验权限
        UserDto currUser = getCurrUser(request);
        String roleName = currUser.getRoleName();
        List<Department> departments = Lists.newArrayList();
        if (SecurityConstant.DJG_ROLE.equals(roleName)){
            PageHelper.startPage(pageNo,pageSize);
            departments = departmentService.getChildrenDept(currUser.getTenantId(),params);
            if (CollUtil.isEmpty(departments)){
                return ReturnT.SUCCESS(departments);
            }
            departments.forEach(department -> {
                Integer fid = department.getFid();
                Department sendDepartment = departmentService.getById(fid);
                Integer ffid = sendDepartment.getFid();
                Department firstDepartment = departmentService.getById(ffid);
                department.setFDeptName(firstDepartment.getDeptName()+"/"+sendDepartment.getDeptName());
            });
        }
        PageInfo<Department> departmentPageInfo = new PageInfo<>(departments);
        return ReturnT.SUCCESS(departmentPageInfo);
    }
    @ApiOperation(value = "根据级别获取组织列表")
    @RequestMapping(value = "/getPrentList",method = RequestMethod.GET)
    public ReturnT<List<DepartmentDto>> getPrentList(HttpServletRequest request,@RequestParam("level") Integer level){
        //校验权限
        UserDto currUser = getCurrUser(request);
        List<Department> departments = Lists.newArrayList();
        if (currUser.getRoleName().equals(SecurityConstant.DJG_ROLE)){
            departments = departmentService.getByLevel(currUser.getTenantId(),level-1);
        }
        if (currUser.getRoleName().equals(SecurityConstant.DZB_ROLE)){
            departments = departmentService.selectByPid(currUser.getDepartment().getId());
        }
        if (currUser.getRoleName().equals(SecurityConstant.DXZ_ROLE)){
            Department department = departmentService.getById(currUser.getDepartment().getId());
            departments.add(department);
        }
        return ReturnT.SUCCESS(departments);
    }

    @ApiOperation(value = "根据级部门父级id获取子集列表")
    @RequestMapping(value = "/getSubList",method = RequestMethod.GET)
    public ReturnT<List<DepartmentDto>> getSubList(HttpServletRequest request,@RequestParam("fid") Integer fid){
        //校验权限
        List<Department> departments = departmentService.selectByPid(fid);
        return ReturnT.SUCCESS(departments);
    }

    @ApiOperation(value = "获取组织的树形数据")
    @RequestMapping(value = "/getTreeList",method = RequestMethod.GET)
    public ReturnT getTreeList(HttpServletRequest request){
        UserDto currUser = getCurrUser(request);
        //校验权限
        List<Department> departments = departmentService.selectTreeList(currUser.getDepartment().getId(),currUser.getTenantId());
        return ReturnT.SUCCESS(departments);
    }

    @ApiOperation(value = "获取所有组织的树形数据")
    @RequestMapping(value = "/getTreeListAll",method = RequestMethod.GET)
    public ReturnT getTreeListAll(HttpServletRequest request){
        //按组织层级节后加载
        UserDto currUser = getCurrUser(request);
        List<Department> departments = departmentService.getByLevel(currUser.getTenantId(),1);
        return ReturnT.SUCCESS(departments);
    }
    @ApiOperation(value = "党组织添加/根据用户角色只能添加自己下级所属的部门")
    @RequestMapping(value = "/add",method = RequestMethod.POST)
    public ReturnT add(@RequestBody DepartmentVo departmentVo, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        String roleName = currUser.getRoleName();
        if (!SecurityConstant.DJG_ROLE.equals(roleName)){
            return ReturnT.FAIL(ReturnT.FAIL_401,"暂无权限");
        }
        //验证管理员是否存在
        User oldUser = userService.selectByUserName(departmentVo.getUserName());
        if (Objects.nonNull(oldUser)){
            return ReturnT.FAIL(ReturnT.FAIL_401,"当前用户名已经存在");
        }
        Department department = new Department();
        department.setTenantId(currUser.getTenantId());
        department.setLevel(departmentVo.getLevel());

        department.setDeptCode("D"+currUser.getTenantId()+ UUIDTools.getNonce_str(7));
        department.setDeptName(departmentVo.getDeptName());
        department.setFid(departmentVo.getFid());
        department.setClerkName(departmentVo.getClerkName());
        department.setCreateName(currUser.getUserName());
        department.setCreateTime(new Date());
        departmentService.save(department);
        //添加部门管理员
        User user = new User();
        user.setTenantId(currUser.getTenantId());
        user.setName(department.getDeptCode());
        user.setUsername(departmentVo.getUserName());
        user.setPassword(SecureUtil.md5(departmentVo.getPwd()));
        user.setDeptId(department.getId());
        if (department.getLevel() == 1){
            user.setRoleName(SecurityConstant.DJG_ROLE);
        }
        if (department.getLevel() == 2){
            user.setRoleName(SecurityConstant.DZB_ROLE);
        }
        if (department.getLevel() == 3){
            user.setRoleName(SecurityConstant.DXZ_ROLE);
        }
        userService.save(user);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "党组织编辑/根据用户角色只能编辑自己下级所属的部门")
    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    public ReturnT edit(@RequestBody DepartmentVo departmentVo, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        String roleName = currUser.getRoleName();
        if (!SecurityConstant.DJG_ROLE.equals(roleName)){
            return ReturnT.FAIL(ReturnT.FAIL_401,"暂无权限");
        }
        //查询用户名是否存在
        User user = userService.selectByDept(departmentVo.getId());
        if (!user.getUsername().equals(departmentVo.getUserName())){
            //验证管理员是否存在
            User oldUser = userService.selectByUserName(departmentVo.getUserName());
            if (Objects.nonNull(oldUser)){
                return ReturnT.FAIL(ReturnT.FAIL_401,"当前用户名已经存在");
            }
        }
        //更新用户信息
        user.setUsername(departmentVo.getUserName());
        userService.updateById(user);
        Department department = departmentService.getById(departmentVo.getId());
        if (Objects.isNull(department)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"组织不存在");
        }
        department.setDeptName(departmentVo.getDeptName());
        department.setUpdateName(currUser.getUserName());
        department.setFid(departmentVo.getFid());
        department.setClerkName(departmentVo.getClerkName());
        department.setLevel(departmentVo.getLevel());
        department.setUpdateTime(new Date());
        departmentService.updateById(department);
        return ReturnT.SUCCESS;
    }

    @ApiOperation(value = "加载部门信息")
    @RequestMapping(value = "/view/{id}",method = RequestMethod.GET)
    public ReturnT view(@PathVariable("id") Integer id, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        String roleName = currUser.getRoleName();
        if (!SecurityConstant.DJG_ROLE.equals(roleName)){
            return ReturnT.FAIL(ReturnT.FAIL_401,"暂无权限");
        }
        Department department = departmentService.getById(id);
        if (Objects.nonNull(department)){
            Department fdept = departmentService.getById(department.getFid());
            if (Objects.nonNull(fdept)){
                department.setFDeptName(fdept.getDeptName());
            }
            User user = userService.selectByDept(department.getId());
            if (Objects.nonNull(user)){
                department.setUserName(user.getUsername());
            }
        }
        return ReturnT.SUCCESS(department);
    }

    @ApiOperation(value = "党组织删除/根据用户角色只能删除自己下级所属的部门")
    @RequestMapping(value = "/delete/{id}",method = RequestMethod.POST)
    public ReturnT delete(@PathVariable("id") Integer id, HttpServletRequest request){
        //校验权限
        UserDto currUser = getCurrUser(request);
        String roleName = currUser.getRoleName();
        if (!SecurityConstant.DJG_ROLE.equals(roleName)){
            return ReturnT.FAIL(ReturnT.FAIL_401,"暂无权限");
        }
        Department department = departmentService.getById(id);
        if (Objects.isNull(department)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"组织不存在");
        }
        List<Department> departments = departmentService.selectByPid(department.getId());
        if (!CollectionUtils.isEmpty(departments)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"当前组织存在子机构");
        }
        //查询当前组织是否关联员工
        List<Employee> employees = employeeService.selectByDeptId(id);
        if (!CollectionUtils.isEmpty(employees)){
            return ReturnT.FAIL(ReturnT.FAIL_CODE,"当前组织存在党员");
        }
        //删除
        departmentService.delete(id);
        //删除用户
        userService.deleteByDept(id);
        return ReturnT.SUCCESS;
    }
}

